import open3d as o3d
import glob
import os

def merge_meshes_from_dense_folder(dense_root="dense", output_filename="combined_mesh.ply"):
    # 搜索所有子目录下的 meshed-poisson.ply
    ply_paths = glob.glob(os.path.join(dense_root, "*", "meshed-poisson.ply"))

    if not ply_paths:
        print("❌ 没有找到任何 meshed-poisson.ply 文件，请检查路径！")
        return

    print(f"✅ 找到 {len(ply_paths)} 个 ply 文件，开始合并...")

    combined_mesh = o3d.geometry.TriangleMesh()

    for ply_file in ply_paths:
        mesh = o3d.io.read_triangle_mesh(ply_file)
        if not mesh.has_vertices():
            print(f"⚠️ 跳过空网格: {ply_file}")
            continue
        print(f"➡️ 合并: {ply_file}，顶点数: {len(mesh.vertices)}")
        combined_mesh += mesh

    print("💾 写入合并结果:", output_filename)
    o3d.io.write_triangle_mesh(output_filename, combined_mesh)
    print("🎉 合并完成！")

# 运行脚本
if __name__ == "__main__":
    dense_root_path = "/data/workspace/3D/room_ws/dense_291_individual"
    output_path = os.path.join(dense_root_path, "combined_mesh.ply")
    merge_meshes_from_dense_folder(dense_root=dense_root_path, output_filename=output_path)
    
    print("execute successful!")
